#include "stdafx.h"
#include "Mutex.h"

namespace Core
{

	Mutex::Mutex() : m_Safe(false)
	{
		pthread_mutex_init(&m_Mutex, NULL);
	}

	Mutex::~Mutex()
	{
		pthread_mutex_destroy(&m_Mutex);
	}

	void Mutex::Lock()
	{
		if(m_Safe) return;
		pthread_mutex_lock(&m_Mutex);
	}

	void Mutex::TimedLock(unsigned short p_MilliSecond)
	{
		if(m_Safe) return;
		timespec t_TimeSpec;
		t_TimeSpec.tv_sec = p_MilliSecond/1000;
		t_TimeSpec.tv_nsec = (p_MilliSecond%1000)*1000000;
		pthread_mutex_timedlock(&m_Mutex, &t_TimeSpec);
	}

	void Mutex::Unlock()
	{
		if(m_Safe) return;
		pthread_mutex_unlock(&m_Mutex);
	}

	bool Mutex::Trylock()
	{
		if(m_Safe) return true;
		return (pthread_mutex_trylock(&m_Mutex)>0?true:false);
	}

	void Mutex::Safe()
	{
		m_Safe = true;
	}

	void Mutex::Unsafe()
	{
		m_Safe = false;
	}

}
